using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using JlPay.Sdk.Core;
using JlPay.Sdk.Services;
using JlPay.Sdk.Models;
using MerchantIncomingModifyRequest = JlPay.Sdk.Models.Merchant.MerchantIncomingModifyRequest;
using MerchantIncomingModifyResponse = JlPay.Sdk.Models.Merchant.MerchantIncomingModifyResponse;

namespace JlPay.Sdk.Examples.Openmerch.Register
{
    /// <summary>
    /// 开放商户 - 商户进件修改功能使用示例
    /// </summary>
    public class MerchantIncomingModifyDemo
    {

        // =================== 常量定义 =====================
        // 产品类型常量
        private const string PRODUCT_TYPE_QR_CODE = "01";  // 扫码商户：适用于码牌类商户，支持微信/支付宝/银联二维码交易
        private const string PRODUCT_TYPE_STANDARD = "02";  // 标准商户：适用于POS类商户，支持银行卡+微信/支付宝/银联二维码交易
        private const string PRODUCT_TYPE_SCENE = "03";  // 场景商户：特定准入商户标准,以人工申请结果为准
        private const string PRODUCT_TYPE_SAAS = "04";  // SaaS商户：适用于SaaS类商户，支持微信/支付宝/银联二维码/银行卡交易

        // 签约模式常量
        private const string SIGN_MODE_PAPER = "P";  // 线下纸质协议
        private const string SIGN_MODE_ELECTRONIC = "E";  // 电子签章协议
        private const string SIGN_MODE_JLPAY = "J";  // 嘉联电子协议

        // 联系人类型常量
        private const string CONTACT_TYPE_LEGAL_PERSON = "65";  // 经营者/法人
        private const string CONTACT_TYPE_OPERATOR = "66";  // 经办人（经商户授权办理支付业务的人员）

        // 商户身份类型常量
        private const string MERCH_TYPE_MICRO = "0";  // 小微
        private const string MERCH_TYPE_ENTERPRISE = "1";  // 营业执照、政府机关、事业单位或其他组织

        // 结算类型常量
        private const string SETTLE_TYPE_LEGAL_PERSON_CARD = "01";  // 打款至法人银行卡
        private const string SETTLE_TYPE_PUBLIC_ACCOUNT = "02";  // 打款至对公账户
        private const string SETTLE_TYPE_PRIVATE_AUTHORIZED = "03";  // 对私授权收款，打款至他人银行卡
        private const string SETTLE_TYPE_PUBLIC_AUTHORIZED = "04";  // 对公授权收款，打款至他人对公账户

        // 结算关系常量
        private const string SETTLE_RELATION_SHAREHOLDERS = "01";  // 股东/雇佣
        private const string SETTLE_RELATION_BRANCHES = "02";  // 总分公司
        private const string SETTLE_RELATION_PARENT_SUBSIDIARY = "03";  // 母子公司
        private const string SETTLE_RELATION_OTHER = "09";  // 其它

        // =================== 工具函数 =====================

        /// <summary>
        /// 处理响应并打印结果
        /// </summary>
        private static void HandleResponse<T>(T response, string operationName) where T : StandardResponse
        {
            if (response.IsSuccess())
            {
                Console.WriteLine($"{operationName}成功！");
                
                // 如果是特定类型的响应，可以进一步解析
                switch (response)
                {
                    case MerchantIncomingModifyResponse modifyResp:
                        Console.WriteLine($"申请单编号: {modifyResp.ApplyId}");
                        break;
                }
            }
            else
            {
                var retCode = response.GetRetCode();
                var retMsg = response.GetRetMsg();
                
                Console.WriteLine($"{operationName}失败: {retCode} - {retMsg}");
            }
        }

        /// <summary>
        /// 根据异常信息获取更准确的错误描述
        /// </summary>
        private static string GetExceptionErrorMessage(Exception ex)
        {
            var message = ex.Message;
            
            // 根据异常消息内容提供更准确的描述
            if (message.Contains("解密失败"))
            {
                return $"字段解密失败: {message}";
            }
            else if (message.Contains("签名验证不通过") || message.Contains("签名失败"))
            {
                return $"签名验证失败: {message}";
            }
            else if (message.Contains("网络") || message.Contains("连接"))
            {
                return $"网络连接错误: {message}";
            }
            else if (message.Contains("超时"))
            {
                return $"请求超时: {message}";
            }
            else if (message.Contains("序列化") || message.Contains("反序列化"))
            {
                return $"数据序列化错误: {message}";
            }
            else
            {
                return message;
            }
        }

        // =================== 商户进件请求构建函数 =====================
        /// <summary>
        /// 构建商户基础信息
        /// </summary>
        private static Dictionary<string, object> BuildBaseInfo(bool isModify = false)
        {
            var applyId = "1vzougr30f9vcw29dc53645a534bc0";
            
            return new Dictionary<string, object>
            {
                ["apply_id"] = applyId,
                ["product_type"] = PRODUCT_TYPE_SAAS,
                ["sign_mode"] = SIGN_MODE_ELECTRONIC,
                ["delegatee_sign_mode"] = SIGN_MODE_ELECTRONIC,
                ["agreement_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
                ["agent_id"] = "50720711",
                ["qrcode_term_auto"] = "1",
                ["contact_info"] = new Dictionary<string, object>
                {
                    ["contact_type"] = CONTACT_TYPE_LEGAL_PERSON,
                    ["contact_name"] = "王一",
                    ["contact_phone"] = "13800138000",
                    ["contact_id_no"] = "110101199003077758"
                }
            };
        }

        /// <summary>
        /// 构建商户身份信息
        /// </summary>
        private static Dictionary<string, object> BuildIdentificationInfo()
        {
            return new Dictionary<string, object>
            {
                ["merch_type"] = MERCH_TYPE_ENTERPRISE,
                ["license_info"] = new Dictionary<string, object>
                {
                    ["license_type"] = "02",  // 企业
                    ["license_name"] = "营业执照上的名称",
                    ["license_no"] = "91330108MABTT5NP6U",
                    ["period_begin"] = "2024-01-01",
                    ["period_end"] = "2030-01-01",
                    ["license_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
                    ["business_scope"] = "经营范围"
                },
                ["identity_info"] = new Dictionary<string, object>
                {
                    ["id_doc_type"] = "01",  // 身份证
                    ["id_card_name"] = "王一",
                    ["id_card_no"] = "110101199003077758",
                    ["legal_person_phone"] = "13800138000",
                    ["card_period_begin"] = "2024-01-01",
                    ["card_period_end"] = "2030-01-01",
                    ["id_card_address"] = "住址",
                    ["id_card_copy"] = "jlpay-test/managefile/2024/02/28/1709081474283_7ddfb60f42d94f8094ec88d7c78ec4a3.png",
                    ["id_card_national"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png"
                }
            };
        }

        /// <summary>
        /// 构建商户经营信息
        /// </summary>
        private static Dictionary<string, object> BuildBusinessInfo()
        {
            return new Dictionary<string, object>
            {
                ["merch_shortname"] = "深圳市泰思便利店",  // 修改商户名称
                ["mcc_code"] = "5311",
                ["address_code"] = "440305",
                ["address_detail"] = "深圳市南山区工业一路22501号",
                ["door_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
                ["indoor_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
                ["cashier_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png"
            };
        }

        /// <summary>
        /// 构建商户结算账户信息
        /// </summary>
        private static Dictionary<string, object> BuildSettlementInfo()
        {
            return new Dictionary<string, object>
            {
                ["settle_type"] = SETTLE_TYPE_LEGAL_PERSON_CARD,
                ["settle_relation"] = SETTLE_RELATION_BRANCHES,
                ["account_info"] = new Dictionary<string, object>
                {
                    ["account_no"] = "6227001215950896532",
                    ["account_name"] = "王一",
                    ["cert_type"] = "01",  // 身份证
                    ["bank_code"] = "082",
                    ["bank_branch_id"] = "105584000370",
                    ["bank_branch_name"] = "中国建设银行股份有限公司深圳罗湖支行",
                    ["account_pic"] = "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg"
                },
                ["other_info"] = new Dictionary<string, object>
                {
                    ["identity_face_pic"] = "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg"
                }
            };
        }

        /// <summary>
        /// 构建费率信息条目
        /// </summary>
        private static Dictionary<string, object> BuildRateInfo(string feeCalcType, string rate, string minAmt = "0", string maxAmt = "-1", 
                                                              string fixedAmt = "0", string bottom = "0", string top = "-1", 
                                                              string step = "0", string baseAmount = "0", string baseFee = "0")
        {
            return new Dictionary<string, object>
            {
                ["fee_calc_type"] = feeCalcType,
                ["rate"] = rate,
                ["min_amt"] = minAmt,
                ["max_amt"] = maxAmt,
                ["fixed"] = fixedAmt,
                ["bottom"] = bottom,
                ["top"] = top,
                ["step"] = step,
                ["base_amount"] = baseAmount,
                ["base_fee"] = baseFee
            };
        }

        /// <summary>
        /// 构建商户结算规则和费率规则
        /// </summary>
        private static Dictionary<string, object> BuildSettlementRule()
        {
            // 根据服务器错误信息，rate_info应该是数组，不是单个对象
            var rateInfo = new List<Dictionary<string, object>>
            {
                BuildRateInfo("30", "0.38"),  // 微信
                BuildRateInfo("31", "0.38"),  // 支付宝
                BuildRateInfo("03", "0.38"),  // 银联二维码（交易金额 <= 1000元）
                BuildRateInfo("66", "0.45", "0", "-1", "0", "0", "1900"),  // 1000元以上银联二维码借记卡 (封顶19元)
                BuildRateInfo("67", "0.55"),  // 1000元以上银联二维码贷记卡 (不封顶)
                BuildRateInfo("01", "0.45", "0", "-1", "0", "0", "1900"),  // 银联内卡借记卡 (封顶19元)
                BuildRateInfo("02", "0.55")   // 银联内卡贷记卡 (不封顶)
            };
            
            return new Dictionary<string, object>
            {
                ["settle_info"] = new Dictionary<string, object>
                {
                    ["settle_mode"] = "7",
                    ["day_cut"] = "000000",
                    ["settle_session"] = "040000",
                    ["account_change_flag"] = "0"
                },
                ["rate_info"] = rateInfo
            };
        }

        /// <summary>
        /// 构建其他附加信息
        /// </summary>
        private static Dictionary<string, object> BuildAdditionalInfo()
        {
            return new Dictionary<string, object>
            {
                ["report_info"] = new Dictionary<string, object>()  // 空对象
            };
        }

        /// <summary>
        /// 构建短信配置
        /// </summary>
        private static Dictionary<string, object> BuildSmsConfig()
        {
            return new Dictionary<string, object>();
        }

        /// <summary>
        /// 构建商户业务功能配置
        /// </summary>
        private static Dictionary<string, object> BuildFuncInfo()
        {
            return new Dictionary<string, object>();
        }

        /// <summary>
        /// 构建品牌连锁商户进件配置信息
        /// </summary>
        private static Dictionary<string, object> BuildChainStoreInfo()
        {
            return new Dictionary<string, object>
            {
                // 可按需添加以下字段
                // ["level"] = "1",
                // ["main_merch_no"] = "12345678",
                // ["at_mode"] = "0"
            };
        }

        /// <summary>
        /// 构建品牌信息
        /// </summary>
        private static Dictionary<string, object> BuildBrandInfo()
        {
            return new Dictionary<string, object>
            {
                // 可按需添加以下字段
                // ["brand_name"] = "XX品牌",
                // ["brand_mark_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
                // ["brand_auth_pic"] = "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
                // ["contact_name"] = "王一",
                // ["contact_phone"] = "13800138000"
            };
        }

        /// <summary>
        /// 构建商户进件修改请求
        /// </summary>
        private static MerchantIncomingModifyRequest BuildMerchantIncomingModifyRequest()
        {
            var request = new MerchantIncomingModifyRequest();
            
            // 使用字典构建请求，与MerchantIncomingAddDemo.cs保持一致
            var requestMap = new Dictionary<string, object>
            {
                ["base_info"] = BuildBaseInfo(true),
                ["identification_info"] = BuildIdentificationInfo(),
                ["business_info"] = BuildBusinessInfo(),
                ["settlement_info"] = BuildSettlementInfo(),
                ["settlement_rule"] = BuildSettlementRule(),
                ["additional_info"] = BuildAdditionalInfo(),
                ["sms_config"] = BuildSmsConfig(),
                ["func_info"] = BuildFuncInfo()
                // ["chain_store_info"] = BuildChainStoreInfo(),
                // ["brand_info"] = BuildBrandInfo()
            };

            // 设置原始请求数据
            request.SetRawRequestMap(requestMap);
            
            return request;
        }

        /// <summary>
        /// 商户进件修改示例
        /// </summary>
        public static async Task MerchantIncomingModifyDemoAsync()
        {
            Console.WriteLine("开始执行商户进件修改示例");

            // 使用DemoConfig创建配置对象
            var config = DemoConfig.CreateConfigWithCrypto();
            Console.WriteLine("配置初始化完成，已启用自动加密和解密功能");

            var merchantService = new MerchantService(config);

            // 创建商户进件修改请求
            var request = BuildMerchantIncomingModifyRequest();

            try
            {
                // 发送请求
                var response = await merchantService.MerchantIncomingModifyAsync(request);

                // 使用自定义的响应处理
                HandleResponse(response, "商户进件修改");
            }
            catch (Exception ex)
            {
                // 根据异常信息提供更准确的错误描述
                var errorMessage = GetExceptionErrorMessage(ex);
                Console.WriteLine($"商户进件修改请求失败: {errorMessage}");
                
                // 如果需要调试，可以输出完整的异常信息
                if (config.Debug)
                {
                    Console.WriteLine($"异常详情: {ex}");
                }
            }

            Console.WriteLine("商户进件修改示例执行完毕");
        }

        /// <summary>
        /// 主程序入口
        /// </summary>
        public static async Task Main(string[] args)
        {
            Console.WriteLine("=" + new string('=', 50));
            Console.WriteLine("===== 商户进件修改示例 开始 =====");
            Console.WriteLine("=" + new string('=', 50));

            await MerchantIncomingModifyDemoAsync();

            Console.WriteLine("=" + new string('=', 50));
            Console.WriteLine("===== 商户进件修改示例执行完毕 =====");
            Console.WriteLine("=" + new string('=', 50));
        }
    }
} 